<?php

namespace app\common\model;

use think\Model;
use think\Db;

/**
 * 基础模型器
 */
class Base extends Model
{
    /**
     * 获取空模型
     */
    public function getEModel($tables)
    {
        $rs  = Db::query('show columns FROM `' . config('database.prefix') . $tables . "`");
        $obj = [];
        if ($rs) {
            foreach ($rs as $key => $v) {
                $obj[$v['Field']] = $v['Default'];
                if ($v['Key'] == 'PRI')
                    $obj[$v['Field']] = 0;
            }
        }
        return $obj;
    }


    public static function getNames($key = null, $val = null)
    {
        $all  = self::order('id', 'desc')->select()->toArray();
        $list = [];
        $key  = $key ?: 'id';
        $val  = $val ?: 'name';
        foreach ($all as $v) {
            $list[$v[$key]] = $v[$val];
        }
        return $list;
    }


    /**
     * 获取所有
     */
    public function getAll()
    {
        return $this->order('id', 'desc')->select()->toArray();
    }


    /**
     * 获取列表
     */
    public function gets($_where = '')
    {
        $where = $this->_where();
        if ($_where)
            $where .= ' AND ' . $_where;

        $page  = input('get.page');
        $limit = input('get.limit');

//        P($where);

        return $this->where($where)->order('id', 'desc')->page($page, $limit)->select()->toArray();
    }


    /**
     * 获取列表的数量
     */
    public function getsCount($_where = '')
    {
        $where = $this->_where();
        if ($_where)
            $where .= ' AND ' . $_where;

        return $this->where($where)->count();
    }


    /**
     * 查询条件的数量
     */
    public function _countWhere($_where = '')
    {
        return $this->where($_where)->count();
    }


    /**
     * 查询条件的条目
     */
    public function _selectWhere($_where = '')
    {
        return $this->where($_where)->select();
    }


    /**
     * 查询单个
     */
    public function _getWhere($_where='')
    {
        return $this->where($_where)->find();
    }

    /**
     * 查询条件
     */
    public function _where()
    {

        $where = ' 1 ';

        if (input('get.key/a')) {
            foreach (input('get.key/a') as $k => $v) {
                if (!empty($v)) {
                    switch ($k) {
                        case "status":
                            $where .= " and {$k}='{$v}'";
                            break;
                        case "time":
                            $applydate = explode("--", $v);
                            $start     = strtotime($applydate[0]);
                            $end       = strtotime($applydate[1]);
                            $where     .= " and '{$start}' <=  unix_timestamp(`time`) and '{$end}' >= unix_timestamp(`time`) ";
                            break;
                    }
                }
            }
        }

        return $where;
    }


    /**
     * 获取单个
     */
    public function getById($id)
    {
        return (Object)$this->where('id', $id)->find()->toArray();
    }


    /**
     * 添加
     */
    public function add($opt)
    {
        $opt['create_at'] = T();

        $result = $this->save($opt);
        if (false !== $result) {
            return [1, "添加成功", $this->id];
        }
        else {
            return [0, $this->getError()];
        }
    }


    public function addAll($opt)
    {
        $result = $this->saveAll($opt);
        if (false !== $result) {
            return [1, "添加成功", $result];
        }
        else {
            return [0, $this->getError()];
        }
    }


    /**
     * 修改
     */
    public function modify($opt, $id)
    {
        $opt['update_at'] = T();

        $result = $this->update($opt, 'id=' . $id);
        if (false !== $result) {
            return [1, "更新成功", []];
        }
        else {
            return [0, $this->getError()];
        }
    }


    /**
     * 条件修改
     */
    public function modify_where($opt, $where)
    {
        $opt['update_at'] = T();

        $result = $this->update($opt, $where);
        if (false !== $result) {
            return [1, "更新成功", []];
        }
        else {
            return [0, $this->getError()];
        }
    }


    /**
     * 删除
     * @param $fake 是否是假删除
     */
    public function remove($id, $fake = false)
    {
        if ($fake === false) {
            $result = $this->destroy($id);
        }
        else {
            $result = $this->modify(['is_del' => 1], $id);
        }

        if (false !== $result) {
            return [1, "删除成功", []];
        }
        else {
            return [0, $this->getError()];
        }
    }


    /**
     * 查询列表
     * @param $pages
     * @param string $where
     * @param string $order
     * @param string $fields
     * @return array|\think\Paginator
     * @throws \think\exception\DbException
     */
    public static function browse($pages, $where = '', $order = '', $fields = '*')
    {
        if (is_array($pages)) {
            return self::where($where)->order($order)->page($pages[0], $pages[1])->paginate()->toArray();
        }
        else {
            return self::where($where)->order($order)->field($fields)->paginate($pages);
        }
    }


    /**
     * 关联查询
     */
    public static function withBrowse($join, $page, $size, $where = '', $order = '', $fields = '*')
    {
        $obj          = [];
        $obj['page']  = $page;
        $obj['size']  = $size;
        $obj['count'] = self::with($join)->where($where)->select()->count();
        $obj['list']  = self::with($join)->where($where)->order($order)->page($page, $size)->select()->toArray();
        return $obj;
    }

}
